package com.yami.shop.mystery.common.listener;

import cn.hutool.core.lang.UUID;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yami.shop.bean.enums.EsOperationType;
import com.yami.shop.bean.event.ActivityProdChangeStatusEvent;
import com.yami.shop.bean.event.ActivityRemoveChangeStatusEvent;
import com.yami.shop.bean.event.EsMysteryBoxUpdateEvent;
import com.yami.shop.bean.event.EsProductUpdateEvent;
import com.yami.shop.bean.model.Product;
import com.yami.shop.common.util.OssMultipartFile;
import com.yami.shop.mystery.common.model.ActivityPresell;
import com.yami.shop.mystery.common.model.MysteryBox;
import com.yami.shop.mystery.common.service.ActivityPresellService;
import com.yami.shop.mystery.common.service.MysteryBoxService;
import com.yami.shop.service.AttachFileService;
import com.yami.shop.service.ProdParameterService;
import com.yami.shop.service.ProductService;
import com.yami.shop.service.SysConfigService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 功能描述: 活动商品修改状态
 * @author wxf
 * @date 2023/6/7 14:51
 */
@Component
public class ActivityProdStatusListener {

    @Autowired
    private ProductService productService;

    @Autowired
    private ApplicationEventPublisher eventPublisher;

    @Autowired
    private ProdParameterService prodParameterService;

    @Autowired
    private MysteryBoxService mysteryBoxService;

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private AttachFileService attachFileService;

    @Autowired
    private ActivityPresellService activityPresellService;

    @EventListener(ActivityProdChangeStatusEvent.class)
    public void apply(ActivityProdChangeStatusEvent event) {

        String activityType = event.getActivityType();
        if (StringUtils.isBlank(activityType)) {
            return;
        }

        if ("1".equals(activityType)) {
            UpdateWrapper<Product> productUpdateWrapper = new UpdateWrapper<>();
            productUpdateWrapper.eq("prod_id",event.getProdId());
            productUpdateWrapper.eq("prod_type",0);
            // 售罄删除状态无法 改为 预售
            productUpdateWrapper.notIn("status",4,-1);

            // 预售商品不修改商品类型以及 活动 Id
            productUpdateWrapper.set("prod_type", 6);
//            productUpdateWrapper.set("activity_id",event.getActivityId());

//            productUpdateWrapper.set("status",9);
            boolean update = productService.update(productUpdateWrapper);
            // 修改ES数据
            if(update){
                removeCache(event.getProdId());
            }
        } else if ("3".equals(activityType)) {
            mysteryBoxService.update(Wrappers.lambdaUpdate(MysteryBox.class)
                    .eq(MysteryBox::getId, event.getProdId()).eq(MysteryBox::getProdType,0)
                    .set(MysteryBox::getProdType, 1).set(MysteryBox::getActivityId, event.getActivityId()));
//                    .set(MysteryBox::getStatus, 9));

            // 修改ES数据
            eventPublisher.publishEvent(new EsMysteryBoxUpdateEvent(event.getProdId(), null, EsOperationType.UPDATE));
        } else if("4".equals(activityType)){
            ActivityPresell activityPresell = activityPresellService.getById(event.getActivityId());
            if(activityPresell.getBlindType() == 0){
                UpdateWrapper<Product> productUpdateWrapper = new UpdateWrapper<>();
                productUpdateWrapper.eq("prod_id",event.getProdId());
                productUpdateWrapper.eq("prod_type",0);
                // 售罄删除状态无法 改为 预售
                productUpdateWrapper.notIn("status",4,-1);
                productUpdateWrapper.set("prod_type", 8);
                productUpdateWrapper.set("activity_id",event.getActivityId());
//                productUpdateWrapper.set("status",9);
                //二维码修改
                Map<String, String> qrcode = createQrcode(event.getProdId(), event.getShopId(),1,event.getActivityId());
                productUpdateWrapper.set("link_addr",qrcode.get("link_addr"));
                productUpdateWrapper.set("qrcode_addr",qrcode.get("qrcode_addr"));
                boolean update = productService.update(productUpdateWrapper);
                // 修改ES数据
                if(update){
                    removeCache(event.getProdId());
                }
            }else{
                Map<String, String> qrcode = createQrcode(event.getProdId(), event.getShopId(),1,event.getActivityId());
                mysteryBoxService.update(Wrappers.lambdaUpdate(MysteryBox.class)
                        .eq(MysteryBox::getId, event.getProdId()).eq(MysteryBox::getProdType,0)
                        .set(MysteryBox::getProdType, 1).set(MysteryBox::getActivityId, event.getActivityId())
                        .set(MysteryBox::getLinkAddr,qrcode.get("link_addr"))
                        .set(MysteryBox::getQrcodeAddr,qrcode.get("qrcode_addr")));
//                        .set(MysteryBox::getStatus, 9));
                // 修改ES数据
                eventPublisher.publishEvent(new EsMysteryBoxUpdateEvent(event.getProdId(), null, EsOperationType.UPDATE));
            }
        }

    }

    @EventListener(ActivityRemoveChangeStatusEvent.class)
    public void removeChangeStatus(ActivityRemoveChangeStatusEvent event) {

        String activityType = event.getActivityType();
        if (StringUtils.isBlank(activityType)) {
            return;
        }
        if ("1".equals(activityType)) {
            UpdateWrapper<Product> productUpdateWrapper = new UpdateWrapper<>();
            productUpdateWrapper.in("prod_id",event.getProdIds());
            productUpdateWrapper.eq("prod_type",6);
            productUpdateWrapper.set("prod_type",event.getProdType());
            productUpdateWrapper.set("activity_id",0);
            productUpdateWrapper.set("status",event.getStatus());
            productService.update(productUpdateWrapper);
            // 修改ES数据
            event.getProdIds().forEach(a -> {
                removeCache(a);
            });
        } else if ("3".equals(activityType)) {
            mysteryBoxService.update(Wrappers.lambdaUpdate(MysteryBox.class)
                    .in(MysteryBox::getId, event.getProdIds()).eq(MysteryBox::getProdType,1)
                    .set(MysteryBox::getProdType, event.getProdType()).set(MysteryBox::getActivityId, 0)
                    .set(MysteryBox::getStatus, event.getStatus()));

            // 修改ES数据
            event.getProdIds().forEach(a -> {
                eventPublisher.publishEvent(new EsMysteryBoxUpdateEvent(a, null, EsOperationType.UPDATE));
            });
        } else if("4".equals(activityType)){

            UpdateWrapper<Product> productUpdateWrapper = new UpdateWrapper<>();
            productUpdateWrapper.in("prod_id",event.getProdIds());
            productUpdateWrapper.eq("prod_type",8);
            productUpdateWrapper.set("prod_type",event.getProdType());
            productUpdateWrapper.set("activity_id",0);
            productUpdateWrapper.set("status",event.getStatus());
            productService.update(productUpdateWrapper);
            for(Long prodId : event.getProdIds()){
                Product product = productService.getById(prodId);
                Map<String, String> qrcode = createQrcode(prodId, product.getShopId(),0,null);
                UpdateWrapper<Product> productUpdate = new UpdateWrapper<>();
                productUpdate.set("link_addr",qrcode.get("link_addr"));
                productUpdate.set("qrcode_addr",qrcode.get("qrcode_addr"));
                productUpdate.eq("prod_id",prodId);
                productService.update(productUpdate);
            }
            // 修改ES数据
            event.getProdIds().forEach(a -> {
                removeCache(a);
            });
        } else if("5".equals(activityType)){
            mysteryBoxService.update(Wrappers.lambdaUpdate(MysteryBox.class)
                    .in(MysteryBox::getId, event.getProdIds())
                    .set(MysteryBox::getProdType, event.getProdType()).set(MysteryBox::getActivityId, 0)
                    .set(MysteryBox::getStatus, event.getStatus()));
            for(Long boxId : event.getProdIds()){
                MysteryBox box = mysteryBoxService.getById(boxId);
                Map<String, String> qrcode = createQrcode(boxId, box.getShopId(),2,null);
                box.setLinkAddr(qrcode.get("link_addr"));
                box.setQrcodeAddr(qrcode.get("qrcode_addr"));
                mysteryBoxService.updateById(box);
            }
            // 修改ES数据
            event.getProdIds().forEach(a -> {
                eventPublisher.publishEvent(new EsMysteryBoxUpdateEvent(a, null, EsOperationType.UPDATE));
            });
        }
    }

    private Map<String,String> createQrcode(Long prodId, Long shopId,int type,Long activityId) {
        Map<String,String> map = new HashMap<>();
        QrConfig config = new QrConfig(300,300);
        BufferedImage qrgenerate = null;
        if(type == 0){
            qrgenerate = QrCodeUtil.generate(sysConfigService.getValue("V_URL")+"/#/?shopId="+shopId+"&prodId="+prodId, config);
            map.put("link_addr",sysConfigService.getValue("V_URL")+"/#/?shopId="+shopId+"&prodId="+prodId);
        }else if(type == 1){
            qrgenerate = QrCodeUtil.generate(sysConfigService.getValue("V_URL")+"/#/?shopId="+shopId+"&prodId="+prodId+"&type=2&activityId="+activityId, config);
            map.put("link_addr",sysConfigService.getValue("V_URL")+"/#/?shopId="+shopId+"&prodId="+prodId+"&type=2&activityId="+activityId);
        }else if(type == 2){
            qrgenerate = QrCodeUtil.generate(sysConfigService.getValue("V_URL")+"/#/?shopId="+shopId+"&prodId="+prodId+"&type=1", config);
            map.put("link_addr",sysConfigService.getValue("V_URL")+"/#/?shopId="+shopId+"&prodId="+prodId+"&type=1");
        }
        //保存图片
        ByteArrayOutputStream qrOutputStream = new ByteArrayOutputStream();
        //读文件
        try {
            ImageIO.write(qrgenerate,"jpg",qrOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        MultipartFile ossMultipartFile = new OssMultipartFile("111.jpg", ".jpg", qrOutputStream.toByteArray());
        try {
            String fileName = attachFileService.uploadFile(ossMultipartFile.getBytes(), UUID.fastUUID()+".jpg");
            // 获取微发行链接地址
            map.put("qrcode_addr",fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }

    // 清除缓存 修改ES
    public void removeCache(Long prodId){
        productService.removeProdCacheByProdId(prodId);
        prodParameterService.removeCacheByProdId(prodId);
        eventPublisher.publishEvent(new EsProductUpdateEvent(prodId, null, EsOperationType.UPDATE));
    }

}
